/**
 * Created by aesop on 2015/4/19.
 */

var the_frame = document.getElementById("theIframe");
var refresh_qr = document.getElementById("refreshQR");
var ensure_submit = document.getElementById("ensureSubmit");
var input_lable = document.getElementsByTagName("input")[0];
var the_id = document.body.getAttribute("data-id") || -1;

var note_link = "";

refresh_qr.onclick = function() {
    var content = the_frame.contentWindow.getContent();
    var title = input_lable.value || "标题";

    if (the_id <= 0) {
        $.post("/note/material/new", {title: title, content: content}, function (data) {
            var obj = JSON.parse(data);
            note_link = location.host + "/note/material/preview?id=" + obj[0];
            document.body.setAttribute("data-id", data[1]);
            the_id = obj[1];
            document.getElementsByTagName("img")[0].src = "http://smeug.nju.edu.cn:7000?text=http://" + note_link;
        })
    }
    else {
        $.post("/note/material/edit?id=" + the_id, {title: title, content: content}, function (data) {
            var obj = JSON.parse(data);
            note_link = location.host + "/note/material/preview?id=" + obj[0];
            document.getElementsByTagName("img")[0].src = "http://smeug.nju.edu.cn:7000?text=http://" + note_link;

        })
    }
}




ensure_submit.onclick = function(){
     var content = the_frame.contentWindow.getContent();
    var title = input_lable.value || "标题";
    ensure_submit.removeEventListener("click");
    ensure_submit.setAttribute("disabled","disabled");
    $.post("/note/material/edit?id=" + the_id, {title: title, content:content},function(data){
        location.href = "/note/material/list";
     });
}

    //如果是编辑状态则获取id
window.onload = function(){
    if(the_id > 0){
        $.get('/note/material/get-json?id=' + the_id,function(result){
            var obj = JSON.parse(result);
            input_lable.value = obj.title;
            the_frame.contentWindow.setContent(obj.content);
        })
    }
}

